cleanup to SpecialUpload.php:
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 * @ingroup Upload
6 *
7 * Form for handling uploads and special page.
8 */
9
10 class SpecialUpload extends SpecialPage {
11 /**
12 * Constructor : initialise object
13 * Get data POSTed through the form and assign them to the object
14 * @param WebRequest $request Data posted.
15 */
16 public function __construct( $request = null ) {
17 global $wgRequest;
18
19 parent::__construct( 'Upload', 'upload' );
20
21 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
22 }
23
24 /** Misc variables **/
25 protected $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
26 protected $mSourceType;
27 protected $mUpload;
28 protected $mLocalFile;
29 protected $mUploadClicked;
30
31 /** User input variables from the "description" section **/
32 public $mDesiredDestName; // The requested target file name
33 protected $mComment;
34 protected $mLicense;
35
36 /** User input variables from the root section **/
37 protected $mIgnoreWarning;
38 protected $mWatchThis;
39 protected $mCopyrightStatus;
40 protected $mCopyrightSource;
41
42 /** Hidden variables **/
43 protected $mDestWarningAck;
44 protected $mForReUpload; // The user followed an "overwrite this file" link
45 protected $mCancelUpload; // The user clicked "Cancel and return to upload form" button
46 protected $mTokenOk;
47 protected $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
48
49 /** Text injection points for hooks not using HTMLForm **/
50 public $uploadFormTextTop;
51 public $uploadFormTextAfterSummary;
52
53 /**
54 * Initialize instance variables from request and create an Upload handler
55 *
56 * @param WebRequest $request The request to extract variables from
57 */
58 protected function loadRequest( $request ) {
59 global $wgUser;
60
61 $this->mRequest = $request;
62 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
63 $this->mUpload = UploadBase::createFromRequest( $request );
64 $this->mUploadClicked = $request->wasPosted()
65 && ( $request->getCheck( 'wpUpload' )
66 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
67
68 // Guess the desired name from the filename if not provided
69 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
70 if( !$this->mDesiredDestName ) {
71 $this->mDesiredDestName = $request->getText( 'wpUploadFile' );
72 }
73 $this->mComment = $request->getText( 'wpUploadDescription' );
74 $this->mLicense = $request->getText( 'wpLicense' );
75
76
77 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
78 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
79 || $request->getCheck( 'wpUploadIgnoreWarning' );
80 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
81 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
82 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
83
84
85 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
86 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
87 || $request->getCheck( 'wpReUpload' ); // b/w compat
88
89 // If it was posted check for the token (no remote POST'ing with user credentials)
90 $token = $request->getVal( 'wpEditToken' );
91 if( $this->mSourceType == 'file' && $token == null ) {
92 // Skip token check for file uploads as that can't be faked via JS...
93 // Some client-side tools don't expect to need to send wpEditToken
94 // with their submissions, as that's new in 1.16.
95 $this->mTokenOk = true;
96 } else {
97 $this->mTokenOk = $wgUser->matchEditToken( $token );
98 }
99
100 $this->uploadFormTextTop = '';
101 $this->uploadFormTextAfterSummary = '';
102 }
103
104 /**
105 * This page can be shown if uploading is enabled.
106 * Handle permission checking elsewhere in order to be able to show
107 * custom error messages.
108 *
109 * @param User $user
110 * @return bool
111 */
112 public function userCanExecute( $user ) {
113 return UploadBase::isEnabled() && parent::userCanExecute( $user );
114 }
115
116 /**
117 * Special page entry point
118 */
119 public function execute( $par ) {
120 global $wgUser, $wgOut, $wgRequest;
121
122 $this->setHeaders();
123 $this->outputHeader();
124
125 # Check uploading enabled
126 if( !UploadBase::isEnabled() ) {
127 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
128 return;
129 }
130
131 # Check permissions
132 global $wgGroupPermissions;
133 if( !$wgUser->isAllowed( 'upload' ) ) {
134 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
135 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
136 // Custom message if logged-in users without any special rights can upload
137 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
138 } else {
139 $wgOut->permissionRequired( 'upload' );
140 }
141 return;
142 }
143
144 # Check blocks
145 if( $wgUser->isBlocked() ) {
146 $wgOut->blockedPage();
147 return;
148 }
149
150 # Check whether we actually want to allow changing stuff
151 if( wfReadOnly() ) {
152 $wgOut->readOnlyPage();
153 return;
154 }
155
156 # Unsave the temporary file in case this was a cancelled upload
157 if ( $this->mCancelUpload ) {
158 if ( !$this->unsaveUploadedFile() ) {
159 # Something went wrong, so unsaveUploadedFile showed a warning
160 return;
161 }
162 }
163
164 # Process upload or show a form
165 if (
166 $this->mTokenOk && !$this->mCancelUpload &&
167 ( $this->mUpload && $this->mUploadClicked )
168 )
169 {
170 $this->processUpload();
171 } else {
172 # Backwards compatibility hook
173 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
174 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
175 return;
176 }
177
178 $this->showUploadForm( $this->getUploadForm() );
179 }
180
181 # Cleanup
182 if ( $this->mUpload ) {
183 $this->mUpload->cleanupTempFile();
184 }
185 }
186
187 /**
188 * Show the main upload form
189 *
190 * @param mixed $form An HTMLForm instance or HTML string to show
191 */
192 protected function showUploadForm( $form ) {
193 # Add links if file was previously deleted
194 if ( !$this->mDesiredDestName ) {
195 $this->showViewDeletedLinks();
196 }
197
198 if ( $form instanceof HTMLForm ) {
199 $form->show();
200 } else {
201 global $wgOut;
202 $wgOut->addHTML( $form );
203 }
204
205 }
206
207 /**
208 * Get an UploadForm instance with title and text properly set.
209 *
210 * @param string $message HTML string to add to the form
211 * @param string $sessionKey Session key in case this is a stashed upload
212 * @return UploadForm
213 */
214 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
215 global $wgOut;
216
217 # Initialize form
218 $form = new UploadForm( array(
219 'watch' => $this->getWatchCheck(),
220 'forreupload' => $this->mForReUpload,
221 'sessionkey' => $sessionKey,
222 'hideignorewarning' => $hideIgnoreWarning,
223 'destwarningack' => (bool)$this->mDestWarningAck,
224
225 'texttop' => $this->uploadFormTextTop,
226 'textaftersummary' => $this->uploadFormTextAfterSummary,
227 ) );
228 $form->setTitle( $this->getTitle() );
229
230 # Check the token, but only if necessary
231 if(
232 !$this->mTokenOk && !$this->mCancelUpload &&
233 ( $this->mUpload && $this->mUploadClicked )
234 )
235 {
236 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
237 }
238
239 # Add text to form
240 $form->addPreText( '<div id="uploadtext">' . wfMsgExt( 'uploadtext', 'parse' ) . '</div>');
241 # Add upload error message
242 $form->addPreText( $message );
243
244 # Add footer to form
245 $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
246 if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) ) {
247 $form->addPostText( '<div id="mw-upload-footer-message">'
248 . $wgOut->parse( $uploadFooter ) . "</div>\n" );
249 }
250
251 return $form;
252
253 }
254
255 /**
256 * Shows the "view X deleted revivions link""
257 */
258 protected function showViewDeletedLinks() {
259 global $wgOut, $wgUser;
260
261 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
262 // Show a subtitle link to deleted revisions (to sysops et al only)
263 if( $title instanceof Title ) {
264 $count = $title->isDeleted();
265 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
266 $link = wfMsgExt(
267 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
268 array( 'parse', 'replaceafter' ),
269 $wgUser->getSkin()->linkKnown(
270 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
271 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
272 )
273 );
274 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
275 }
276 }
277
278 // Show the relevant lines from deletion log (for still deleted files only)
279 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
280 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
281 }
282 }
283
284 /**
285 * Stashes the upload and shows the main upload form.
286 *
287 * Note: only errors that can be handled by changing the name or
288 * description should be redirected here. It should be assumed that the
289 * file itself is sane and has passed UploadBase::verifyFile. This
290 * essentially means that UploadBase::VERIFICATION_ERROR and
291 * UploadBase::EMPTY_FILE should not be passed here.
292 *
293 * @param string $message HTML message to be passed to mainUploadForm
294 */
295 protected function showRecoverableUploadError( $message ) {
296 $sessionKey = $this->mUpload->stashSession();
297 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
298 '<div class="error">' . $message . "</div>\n";
299
300 $form = $this->getUploadForm( $message, $sessionKey );
301 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
302 $this->showUploadForm( $form );
303 }
304 /**
305 * Stashes the upload, shows the main form, but adds an "continue anyway button".
306 * Also checks whether there are actually warnings to display.
307 *
308 * @param array $warnings
309 * @return boolean true if warnings were displayed, false if there are no
310 * warnings and the should continue processing like there was no warning
311 */
312 protected function showUploadWarning( $warnings ) {
313 # If there are no warnings, or warnings we can ignore, return early
314 if (
315 !$warnings || ( count( $warnings ) == 1 &&
316 isset( $warnings['exists']) && $this->mDestWarningAck )
317 )
318 {
319 return false;
320 }
321
322 $sessionKey = $this->mUpload->stashSession();
323
324 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
325 . '<ul class="warning">';
326 foreach( $warnings as $warning => $args ) {
327 $msg = '';
328 if( $warning == 'exists' ) {
329 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
330 } elseif( $warning == 'duplicate' ) {
331 $msg = self::getDupeWarning( $args );
332 } elseif( $warning == 'duplicate-archive' ) {
333 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
334 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
335 . "</li>\n";
336 } else {
337 if ( $args === true ) {
338 $args = array();
339 } elseif ( !is_array( $args ) ) {
340 $args = array( $args );
341 }
342 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
343 }
344 $warningHtml .= $msg;
345 }
346 $warningHtml .= "</ul>\n";
347 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
348
349 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
350 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
351 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
352 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
353
354 $this->showUploadForm( $form );
355
356 # Indicate that we showed a form
357 return true;
358 }
359
360 /**
361 * Show the upload form with error message, but do not stash the file.
362 *
363 * @param string $message
364 */
365 protected function showUploadError( $message ) {
366 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
367 '<div class="error">' . $message . "</div>\n";
368 $this->showUploadForm( $this->getUploadForm( $message ) );
369 }
370
371 /**
372 * Do the upload.
373 * Checks are made in SpecialUpload::execute()
374 */
375 protected function processUpload() {
376 global $wgUser, $wgOut;
377
378 // Verify permissions
379 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
380 if( $permErrors !== true ) {
381 $wgOut->showPermissionsErrorPage( $permErrors );
382 return;
383 }
384
385 // Fetch the file if required
386 $status = $this->mUpload->fetchFile();
387 if( !$status->isOK() ) {
388 $this->showUploadForm( $this->getUploadForm( $wgOut->parse( $status->getWikiText() ) ) );
389 return;
390 }
391
392 // Deprecated backwards compatibility hook
393 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
394 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
395 return array( 'status' => UploadBase::BEFORE_PROCESSING );
396 }
397
398
399 // Upload verification
400 $details = $this->mUpload->verifyUpload();
401 if ( $details['status'] != UploadBase::OK ) {
402 $this->processVerificationError( $details );
403 return;
404 }
405
406 $this->mLocalFile = $this->mUpload->getLocalFile();
407
408 // Check warnings if necessary
409 if( !$this->mIgnoreWarning ) {
410 $warnings = $this->mUpload->checkWarnings();
411 if( $this->showUploadWarning( $warnings ) ) {
412 return;
413 }
414 }
415
416 // Get the page text if this is not a reupload
417 if( !$this->mForReUpload ) {
418 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
419 $this->mCopyrightStatus, $this->mCopyrightSource );
420 } else {
421 $pageText = false;
422 }
423 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
424 if ( !$status->isGood() ) {
425 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
426 return;
427 }
428
429 // Success, redirect to description page
430 $this->mUploadSuccessful = true;
431 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
432 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
433 }
434
435 /**
436 * Get the initial image page text based on a comment and optional file status information
437 */
438 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
439 global $wgUseCopyrightUpload;
440 if ( $wgUseCopyrightUpload ) {
441 $licensetxt = '';
442 if ( $license != '' ) {
443 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
444 }
445 $pageText = '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n" .
446 '== ' . wfMsgForContent( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
447 "$licensetxt" .
448 '== ' . wfMsgForContent( 'filesource' ) . " ==\n" . $source;
449 } else {
450 if ( $license != '' ) {
451 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n";
452 $pageText = $filedesc .
453 '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
454 } else {
455 $pageText = $comment;
456 }
457 }
458 return $pageText;
459 }
460
461 /**
462 * See if we should check the 'watch this page' checkbox on the form
463 * based on the user's preferences and whether we're being asked
464 * to create a new file or update an existing one.
465 *
466 * In the case where 'watch edits' is off but 'watch creations' is on,
467 * we'll leave the box unchecked.
468 *
469 * Note that the page target can be changed *on the form*, so our check
470 * state can get out of sync.
471 */
472 protected function getWatchCheck() {
473 global $wgUser;
474 if( $wgUser->getOption( 'watchdefault' ) ) {
475 // Watch all edits!
476 return true;
477 }
478
479 $local = wfLocalFile( $this->mDesiredDestName );
480 if( $local && $local->exists() ) {
481 // We're uploading a new version of an existing file.
482 // No creation, so don't watch it if we're not already.
483 return $local->getTitle()->userIsWatching();
484 } else {
485 // New page should get watched if that's our option.
486 return $wgUser->getOption( 'watchcreations' );
487 }
488 }
489
490
491 /**
492 * Provides output to the user for a result of UploadBase::verifyUpload
493 *
494 * @param array $details Result of UploadBase::verifyUpload
495 */
496 protected function processVerificationError( $details ) {
497 global $wgFileExtensions, $wgLang;
498
499 switch( $details['status'] ) {
500
501 /** Statuses that only require name changing **/
502 case UploadBase::MIN_LENGTH_PARTNAME:
503 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
504 break;
505 case UploadBase::ILLEGAL_FILENAME:
506 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
507 'parseinline', $details['filtered'] ) );
508 break;
509 case UploadBase::OVERWRITE_EXISTING_FILE:
510 $this->showRecoverableUploadError( wfMsgExt( $details['overwrite'],
511 'parseinline' ) );
512 break;
513 case UploadBase::FILETYPE_MISSING:
514 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
515 'parseinline' ) );
516 break;
517
518 /** Statuses that require reuploading **/
519 case UploadBase::EMPTY_FILE:
520 $this->showUploadForm( $this->getUploadForm( wfMsgHtml( 'emptyfile' ) ) );
521 break;
522 case UploadBase::FILETYPE_BADTYPE:
523 $finalExt = $details['finalExt'];
524 $this->showUploadError(
525 wfMsgExt( 'filetype-banned-type',
526 array( 'parseinline' ),
527 htmlspecialchars( $finalExt ),
528 implode(
529 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
530 $wgFileExtensions
531 ),
532 $wgLang->formatNum( count( $wgFileExtensions ) )
533 )
534 );
535 break;
536 case UploadBase::VERIFICATION_ERROR:
537 unset( $details['status'] );
538 $code = array_shift( $details['details'] );
539 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
540 break;
541 case UploadBase::HOOK_ABORTED:
542 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
543 $args = $details['error'];
544 $error = array_shift( $args );
545 } else {
546 $error = $details['error'];
547 $args = null;
548 }
549
550 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
551 break;
552 default:
553 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
554 }
555 }
556
557 /**
558 * Remove a temporarily kept file stashed by saveTempUploadedFile().
559 * @return success
560 */
561 protected function unsaveUploadedFile() {
562 global $wgOut;
563 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
564 return true;
565 }
566 $success = $this->mUpload->unsaveUploadedFile();
567 if ( !$success ) {
568 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
569 return false;
570 } else {
571 return true;
572 }
573 }
574
575 /*** Functions for formatting warnings ***/
576
577 /**
578 * Formats a result of UploadBase::getExistsWarning as HTML
579 * This check is static and can be done pre-upload via AJAX
580 *
581 * @param array $exists The result of UploadBase::getExistsWarning
582 * @return string Empty string if there is no warning or an HTML fragment
583 */
584 public static function getExistsWarning( $exists ) {
585 global $wgUser, $wgContLang;
586
587 if ( !$exists ) {
588 return '';
589 }
590
591 $file = $exists['file'];
592 $filename = $file->getTitle()->getPrefixedText();
593 $warning = '';
594
595 $sk = $wgUser->getSkin();
596
597 if( $exists['warning'] == 'exists' ) {
598 // Exact match
599 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
600 } elseif( $exists['warning'] == 'page-exists' ) {
601 // Page exists but file does not
602 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
603 } elseif ( $exists['warning'] == 'exists-normalized' ) {
604 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
605 $exists['normalizedFile']->getTitle()->getPrefixedText() );
606 } elseif ( $exists['warning'] == 'thumb' ) {
607 // Swapped argument order compared with other messages for backwards compatibility
608 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
609 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
610 } elseif ( $exists['warning'] == 'thumb-name' ) {
611 // Image w/o '180px-' does not exists, but we do not like these filenames
612 $name = $file->getName();
613 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
614 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
615 } elseif ( $exists['warning'] == 'bad-prefix' ) {
616 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
617 } elseif ( $exists['warning'] == 'was-deleted' ) {
618 # If the file existed before and was deleted, warn the user of this
619 $ltitle = SpecialPage::getTitleFor( 'Log' );
620 $llink = $sk->linkKnown(
621 $ltitle,
622 wfMsgHtml( 'deletionlog' ),
623 array(),
624 array(
625 'type' => 'delete',
626 'page' => $filename
627 )
628 );
629 $warning = wfMsgWikiHtml( 'filewasdeleted', $llink );
630 }
631
632 return $warning;
633 }
634
635 /**
636 * Get a list of warnings
637 *
638 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
639 * @return array list of warning messages
640 */
641 public static function ajaxGetExistsWarning( $filename ) {
642 $file = wfFindFile( $filename );
643 if( !$file ) {
644 // Force local file so we have an object to do further checks against
645 // if there isn't an exact match...
646 $file = wfLocalFile( $filename );
647 }
648 $s = '&nbsp;';
649 if ( $file ) {
650 $exists = UploadBase::getExistsWarning( $file );
651 $warning = self::getExistsWarning( $exists );
652 if ( $warning !== '' ) {
653 $s = "<div>$warning</div>";
654 }
655 }
656 return $s;
657 }
658
659 /**
660 * Construct a warning and a gallery from an array of duplicate files.
661 */
662 public static function getDupeWarning( $dupes ) {
663 if( $dupes ) {
664 global $wgOut;
665 $msg = '<gallery>';
666 foreach( $dupes as $file ) {
667 $title = $file->getTitle();
668 $msg .= $title->getPrefixedText() .
669 '|' . $title->getText() . "\n";
670 }
671 $msg .= '</gallery>';
672 return '<li>' .
673 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
674 $wgOut->parse( $msg ) .
675 "</li>\n";
676 } else {
677 return '';
678 }
679 }
680
681 }
682
683 /**
684 * Sub class of HTMLForm that provides the form section of SpecialUpload
685 */
686 class UploadForm extends HTMLForm {
687 protected $mWatch;
688 protected $mForReUpload;
689 protected $mSessionKey;
690 protected $mHideIgnoreWarning;
691 protected $mDestWarningAck;
692
693 protected $mTextTop;
694 protected $mTextAfterSummary;
695
696 protected $mSourceIds;
697
698 public function __construct( $options = array() ) {
699 $this->mWatch = !empty( $options['watch'] );
700 $this->mForReUpload = !empty( $options['forreupload'] );
701 $this->mSessionKey = isset( $options['sessionkey'] )
702 ? $options['sessionkey'] : '';
703 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
704 $this->mDestWarningAck = !empty( $options['destwarningack'] );
705
706 $this->mTextTop = $options['texttop'];
707 $this->mTextAfterSummary = $options['textaftersummary'];
708
709 $sourceDescriptor = $this->getSourceSection();
710 $descriptor = $sourceDescriptor
711 + $this->getDescriptionSection()
712 + $this->getOptionsSection();
713
714 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
715 parent::__construct( $descriptor, 'upload' );
716
717 # Set some form properties
718 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
719 $this->setSubmitName( 'wpUpload' );
720 $this->setSubmitTooltip( 'upload' );
721 $this->setId( 'mw-upload-form' );
722
723 # Build a list of IDs for javascript insertion
724 $this->mSourceIds = array();
725 foreach ( $sourceDescriptor as $key => $field ) {
726 if ( !empty( $field['id'] ) ) {
727 $this->mSourceIds[] = $field['id'];
728 }
729 }
730
731 }
732
733 /**
734 * Get the descriptor of the fieldset that contains the file source
735 * selection. The section is 'source'
736 *
737 * @return array Descriptor array
738 */
739 protected function getSourceSection() {
740 global $wgLang, $wgUser, $wgRequest;
741
742 if ( $this->mSessionKey ) {
743 return array(
744 'wpSessionKey' => array(
745 'type' => 'hidden',
746 'default' => $this->mSessionKey,
747 ),
748 'wpSourceType' => array(
749 'type' => 'hidden',
750 'default' => 'Stash',
751 ),
752 );
753 }
754
755 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
756 $radio = $canUploadByUrl;
757 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
758
759 $descriptor = array();
760 if ( $this->mTextTop ) {
761 $descriptor['UploadFormTextTop'] = array(
762 'type' => 'info',
763 'section' => 'source',
764 'default' => $this->mTextTop,
765 'raw' => true,
766 );
767 }
768
769 $descriptor['UploadFile'] = array(
770 'class' => 'UploadSourceField',
771 'section' => 'source',
772 'type' => 'file',
773 'id' => 'wpUploadFile',
774 'label-message' => 'sourcefilename',
775 'upload-type' => 'File',
776 'radio' => &$radio,
777 'help' => wfMsgExt( 'upload-maxfilesize',
778 array( 'parseinline', 'escapenoentities' ),
779 $wgLang->formatSize(
780 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) )
781 )
782 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
783 'checked' => $selectedSourceType == 'file',
784 );
785 if ( $canUploadByUrl ) {
786 global $wgMaxUploadSize;
787 $descriptor['UploadFileURL'] = array(
788 'class' => 'UploadSourceField',
789 'section' => 'source',
790 'id' => 'wpUploadFileURL',
791 'label-message' => 'sourceurl',
792 'upload-type' => 'url',
793 'radio' => &$radio,
794 'help' => wfMsgExt( 'upload-maxfilesize',
795 array( 'parseinline', 'escapenoentities' ),
796 $wgLang->formatSize( $wgMaxUploadSize )
797 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
798 'checked' => $selectedSourceType == 'url',
799 );
800 }
801 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
802
803 $descriptor['Extensions'] = array(
804 'type' => 'info',
805 'section' => 'source',
806 'default' => $this->getExtensionsMessage(),
807 'raw' => true,
808 );
809 return $descriptor;
810 }
811
812 /**
813 * Get the messages indicating which extensions are preferred and prohibitted.
814 *
815 * @return string HTML string containing the message
816 */
817 protected function getExtensionsMessage() {
818 # Print a list of allowed file extensions, if so configured. We ignore
819 # MIME type here, it's incomprehensible to most people and too long.
820 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
821 $wgFileExtensions, $wgFileBlacklist;
822
823 $allowedExtensions = '';
824 if( $wgCheckFileExtensions ) {
825 if( $wgStrictFileExtensions ) {
826 # Everything not permitted is banned
827 $extensionsList =
828 '<div id="mw-upload-permitted">' .
829 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
830 "</div>\n";
831 } else {
832 # We have to list both preferred and prohibited
833 $extensionsList =
834 '<div id="mw-upload-preferred">' .
835 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
836 "</div>\n" .
837 '<div id="mw-upload-prohibited">' .
838 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
839 "</div>\n";
840 }
841 } else {
842 # Everything is permitted.
843 $extensionsList = '';
844 }
845 return $extensionsList;
846 }
847
848 /**
849 * Get the descriptor of the fieldset that contains the file description
850 * input. The section is 'description'
851 *
852 * @return array Descriptor array
853 */
854 protected function getDescriptionSection() {
855 global $wgUser, $wgOut;
856
857 $cols = intval( $wgUser->getOption( 'cols' ) );
858 if( $wgUser->getOption( 'editwidth' ) ) {
859 $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
860 }
861
862 $descriptor = array(
863 'DestFile' => array(
864 'type' => 'text',
865 'section' => 'description',
866 'id' => 'wpDestFile',
867 'label-message' => 'destfilename',
868 'size' => 60,
869 ),
870 'UploadDescription' => array(
871 'type' => 'textarea',
872 'section' => 'description',
873 'id' => 'wpUploadDescription',
874 'label-message' => $this->mForReUpload
875 ? 'filereuploadsummary'
876 : 'fileuploadsummary',
877 'cols' => $cols,
878 'rows' => 8,
879 )
880 );
881 if ( $this->mTextAfterSummary ) {
882 $descriptor['UploadFormTextAfterSummary'] = array(
883 'type' => 'info',
884 'section' => 'description',
885 'default' => $this->mTextAfterSummary,
886 'raw' => true,
887 );
888 }
889
890 $descriptor += array(
891 'EditTools' => array(
892 'type' => 'edittools',
893 'section' => 'description',
894 ),
895 'License' => array(
896 'type' => 'select',
897 'class' => 'Licenses',
898 'section' => 'description',
899 'id' => 'wpLicense',
900 'label-message' => 'license',
901 ),
902 );
903 if ( $this->mForReUpload ) {
904 $descriptor['DestFile']['readonly'] = true;
905 }
906
907 global $wgUseCopyrightUpload;
908 if ( $wgUseCopyrightUpload ) {
909 $descriptor['UploadCopyStatus'] = array(
910 'type' => 'text',
911 'section' => 'description',
912 'id' => 'wpUploadCopyStatus',
913 'label-message' => 'filestatus',
914 );
915 $descriptor['UploadSource'] = array(
916 'type' => 'text',
917 'section' => 'description',
918 'id' => 'wpUploadSource',
919 'label-message' => 'filesource',
920 );
921 }
922
923 return $descriptor;
924 }
925
926 /**
927 * Get the descriptor of the fieldset that contains the upload options,
928 * such as "watch this file". The section is 'options'
929 *
930 * @return array Descriptor array
931 */
932 protected function getOptionsSection() {
933 global $wgUser;
934
935 if( $wgUser->isLoggedIn() ) {
936 $descriptor = array(
937 'Watchthis' => array(
938 'type' => 'check',
939 'id' => 'wpWatchthis',
940 'label-message' => 'watchthisupload',
941 'section' => 'options',
942 )
943 );
944 }
945 if( !$this->mHideIgnoreWarning ) {
946 $descriptor['IgnoreWarning'] = array(
947 'type' => 'check',
948 'id' => 'wpIgnoreWarning',
949 'label-message' => 'ignorewarnings',
950 'section' => 'options',
951 );
952 }
953
954 $descriptor['wpDestFileWarningAck'] = array(
955 'type' => 'hidden',
956 'id' => 'wpDestFileWarningAck',
957 'default' => $this->mDestWarningAck ? '1' : '',
958 );
959
960 return $descriptor;
961 }
962
963 /**
964 * Add the upload JS and show the form.
965 */
966 public function show() {
967 $this->addUploadJS();
968 parent::show();
969 }
970
971 /**
972 * Add upload JS to $wgOut
973 *
974 * @param $autofill Boolean: Whether or not to autofill the destination
975 * filename text box
976 */
977 protected function addUploadJS() {
978 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI;
979 global $wgOut;
980
981 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
982 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
983
984 $scriptVars = array(
985 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
986 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
987 'wgUploadAutoFill' => !$this->mForReUpload,
988 'wgUploadSourceIds' => $this->mSourceIds,
989 );
990
991 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
992
993 // For <charinsert> support
994 $wgOut->addScriptFile( 'edit.js' );
995 $wgOut->addScriptFile( 'upload.js' );
996 }
997
998 /**
999 * Empty function; submission is handled elsewhere.
1000 *
1001 * @return bool false
1002 */
1003 function trySubmit() {
1004 return false;
1005 }
1006
1007 }
1008
1009 /**
1010 * A form field that contains a radio box in the label
1011 */
1012 class UploadSourceField extends HTMLTextField {
1013 function getLabelHtml() {
1014 $id = "wpSourceType{$this->mParams['upload-type']}";
1015 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1016
1017 if ( !empty( $this->mParams['radio'] ) ) {
1018 $attribs = array(
1019 'name' => 'wpSourceType',
1020 'type' => 'radio',
1021 'id' => $id,
1022 'value' => $this->mParams['upload-type'],
1023 );
1024 if ( !empty( $this->mParams['checked'] ) ) {
1025 $attribs['checked'] = 'checked';
1026 }
1027 $label .= Html::element( 'input', $attribs );
1028 }
1029
1030 return Html::rawElement( 'td', array( 'class' => 'mw-label' ), $label );
1031 }
1032
1033 function getSize() {
1034 return isset( $this->mParams['size'] )
1035 ? $this->mParams['size']
1036 : 60;
1037 }
1038 }
1039